package com.lt.app;

import android.app.Activity;
import android.text.TextUtils;

import com.lt.common.DebugHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 下载更新APK的工具
 */
public class InstallHelper
{


    //任务定时器
    private Timer mTimer;
    //定时任务
    private TimerTask mTask;
    //文件总大小
    private int fileLength = 1;
    //下载的文件大小
    private int fileCurrentLength;

    private Activity mActivity;
    private String httpUrl;
    private String savePath;
    private String saveName;
    private DownloadCallBack downloadCallBack;
    private static File saveFile;

    private boolean isComplete = false;


    public interface DownloadCallBack
    {
        void onStart();

        void onComplete(String path);

        void onLoading(long total, long current);

        void onFail(String err);
    }

    public InstallHelper(Activity act, String httpUrl, String dir, String saveName, DownloadCallBack downloadCallBack)
    {
        this.mActivity = act;
        this.httpUrl = httpUrl;
        this.saveName = saveName;
        this.downloadCallBack = downloadCallBack;
        this.savePath = dir;
    }


    public void downloadAPK()
    {
        DebugHelper.e("downloadAPK");
        if (TextUtils.isEmpty(httpUrl))
        {
            sendErr("下载链接错误");
            return;
        }
        saveFile = new File(savePath);
        if (!saveFile.exists())
        {
            boolean isMK = saveFile.mkdirs();
            if (!isMK)
            {
                //创建失败
                sendErr("权限异常，创建文件夹失败");
                return;
            }
        }
        saveFile = new File(savePath + saveName);
        DebugHelper.e("saveFile" + saveFile);
        if (saveFile.exists())
        {
            try
            {
                saveFile.delete();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        if (downloadCallBack != null)
        {
            //下载开始
            downloadCallBack.onStart();
        }

        new Thread(() ->
        {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            HttpURLConnection connection = null;
            try
            {
                URL url = new URL(httpUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(10 * 1000);
                connection.setReadTimeout(10 * 1000);
                connection.connect();
                inputStream = connection.getInputStream();
                outputStream = new FileOutputStream(saveFile);
                fileLength = connection.getContentLength();

                //计时器
                initTimer();

                byte[] buffer = new byte[1024];
                int current = 0;
                int len;
                while ((len = inputStream.read(buffer)) > 0)
                {
                    outputStream.write(buffer, 0, len);
                    current += len;
                    if (fileLength > 0)
                    {
                        fileCurrentLength = current;
                    }
                }
                isComplete = true;
                //下载完成
                mActivity.runOnUiThread(() ->
                {
                    if (downloadCallBack != null)
                    {
                        downloadCallBack.onComplete(saveFile.getPath());
                        downloadCallBack = null;
                    }
                });
            } catch (final Exception e)
            {
                e.printStackTrace();
                sendErr("下载文件出现错误");
            } finally
            {
                try
                {
                    if (inputStream != null)
                        inputStream.close();
                    if (outputStream != null)
                        outputStream.close();
                    if (connection != null)
                        connection.disconnect();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
                //销毁Timer
                destroyTimer();
            }
        }).start();

    }

    private void initTimer()
    {
        mTimer = new Timer();
        mTask = new TimerTask()
        {//在run方法中执行定时的任务
            @Override
            public void run()
            {
                mActivity.runOnUiThread(() ->
                {
                    if (downloadCallBack != null)
                    {
                        if (!isComplete)
                        {
                            downloadCallBack.onLoading(fileLength, fileCurrentLength);
                        }
                    }
                });
            }
        };
        //任务定时器一定要启动
        mTimer.schedule(mTask, 0, 200);
    }


    private void destroyTimer()
    {
        if (mTimer != null && mTask != null)
        {
            mTask.cancel();
            mTimer.cancel();
            mTask = null;
            mTimer = null;
        }
    }

    private void sendErr(String err)
    {
        mActivity.runOnUiThread(() ->
        {
            if (downloadCallBack != null)
            {
                downloadCallBack.onFail(err);
                downloadCallBack = null;
            }
        });
    }
}
